package kael.aiur.dao;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
	private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	private static final String USER = "sa";
	private static final String PASSWORD = "sa";
	private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=";
	private static String DATABASE = "master";
	static{
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public Connection getConn(String database){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL+database,USER,PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{}
		return conn;
	}
	public Connection getConn(){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL+DATABASE,USER,PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{}
		return conn;
	}
	public PreparedStatement getPstmt(Connection conn,String sql){
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return pstmt;
	}
	public PreparedStatement excPstmt(PreparedStatement pstmt, Object[] value){
		try {
			for(int i = 0; i < value.length;i++){
				pstmt.setObject(i, value[i]);
			}
			pstmt.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return pstmt;
	}
	public Statement getStmt(Connection conn){
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}
	public Statement excUpdateStmt(Statement stmt,String sql){
		try {
			stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}
	public ResultSet excQueryStmt(Statement stmt,String sql){
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	public void closeResource(Connection conn, PreparedStatement pstmt, Statement stmt, ResultSet rs){
		try {
			if(rs != null){
				rs.close();
			}
			if(stmt != null){
				stmt.close();		
			}
			if(pstmt != null){
				pstmt.close();
			}
			if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
